package com.qding.park.manager.service.statis.biz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import com.qding.park.common.core.constant.MongodbConstant;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.facade.statis.service.StatisticsReportFacade.InterMonth;
import com.qding.park.manager.facade.statis.service.StatisticsReportFacade.PassMonth;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.enums.ButtonTypeEnum;
import com.qding.park.manager.pojo.example.StatisInterMonthExample;
import com.qding.park.manager.pojo.example.StatisPassMonthExample;
import com.qding.park.manager.pojo.noncore.NcPassDayReport;

@Component("statisticsReportBiz_statis")
public class StatisticsReportBiz {

	private static final Logger _log = LoggerFactory.getLogger(StatisticsReportBiz.class);

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Autowired
	private ParkCacheInter  parkCacheInter;

	public int interMonth_segment_total(StatisInterMonthExample example) {
		// String tablename_terminallog = MongodbConstant.TABLENAME_TERMINALLOG;
		// List<AggregationOperation>
		// aggOperList=buildAggredation_interMonth_segment(example);
		// Aggregation agg=Aggregation.newAggregation(aggOperList);
		// AggregationResults<DBObject> aggResult = mongoTemplate.aggregate(agg,
		// tablename_terminallog, DBObject.class);
		// return aggResult.getMappedResults().size();
		return 1;
	}

	public int passMonth_segment_total(StatisPassMonthExample example) {
		// 表名
		String tablenamePassDay = MongodbConstant.TABLENAME_PASS_DAY_REPORT;
		// 得到日期字符串
		List<PassMonth> result = new ArrayList<PassMonth>();
		Criteria matchCrieria = new Criteria();
		List<Integer> parkIdlist = new ArrayList<Integer>();
		matchCrieria.where("_id").not();
		if (example.getStartTime() != null && example.getEndTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").gte(example.getStartTime()),
					Criteria.where("oPTime").lte(example.getEndTime()));
		} else if (example.getStartTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").gte(example.getStartTime()));
		} else if (example.getEndTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").lte(example.getEndTime()));
		}

		if (example.getParkId() != null) {
			parkIdlist.add(example.getParkId());
		} else if (!ListUtil.isEmpty(example.getInParks())) {
			parkIdlist.addAll(example.getInParks());
		}
		if (!ListUtil.isEmpty(parkIdlist)) {
			matchCrieria.and("parkId").in(parkIdlist);
		}

		// 构建查询条件

		Query query = Query.query(matchCrieria);

		int total = (int) mongoTemplate.count(query, tablenamePassDay);
		return total;
	}

	public int interMonth_month_total(StatisInterMonthExample example) {
		String tablename_terminallog = MongodbConstant.TABLENAME_TERMINALLOG;
		List<AggregationOperation> aggOperList = buildAggredation_interMonth(example);
		Aggregation agg = Aggregation.newAggregation(aggOperList);
		AggregationResults<DBObject> aggResult = mongoTemplate.aggregate(agg, tablename_terminallog, DBObject.class);
		return aggResult.getMappedResults().size();
	}

	public int passMonth_month_total(StatisPassMonthExample example) {
		String tablename = MongodbConstant.TABLENAME_PASS_DAY_REPORT;
		List<AggregationOperation> aggOperList = buildAggredation_passMonth(example);
		Aggregation agg = Aggregation.newAggregation(aggOperList);
		AggregationResults<DBObject> aggResult = mongoTemplate.aggregate(agg, tablename, DBObject.class);
		return aggResult.getMappedResults().size();
	}

	private List<AggregationOperation> buildAggredation_interMonth(StatisInterMonthExample example) {
		Criteria matchCrieria = new Criteria();
		List<String> parkIdlist = new ArrayList<String>();
		
		if(!StringUtils.isBlank(example.getParkId())){
			parkIdlist.add(example.getParkId());
		}else if(!ListUtil.isEmpty(example.getInParks())){
			parkIdlist.addAll(example.getStrInParks());
		}
//		if (!ListUtil.isEmpty(example.getInParks())) {
//			parkIdlist.addAll(example.getInParks());
//		}
//		if (!StringUtils.isBlank(example.getParkId()) && !parkIdlist.contains(Integer.valueOf(example.getParkId()))) {
//			parkIdlist.add(Integer.valueOf(example.getParkId()));
//		}

//		if (!ListUtil.isEmpty(parkIdlist)) {
////			matchCrieria.and("parkIds").in(parkIdlist);
//			matchCrieria.and("parkId").in(parkIdlist);
//		}
		if (!ListUtil.isEmpty(parkIdlist)&&!ListUtil.isEmpty(example.getNoInParks())) {
			matchCrieria.andOperator(Criteria.where("parkId").in(parkIdlist),Criteria.where("parkId").nin(example.getNoInParks()));
		}else if(!ListUtil.isEmpty(parkIdlist)){
			matchCrieria.and("parkId").in(parkIdlist);
		}else if(!ListUtil.isEmpty(example.getNoInParks())){
			matchCrieria.and("parkId").nin(example.getNoInParks());
		}

		StringBuffer projectJsonStr = new StringBuffer();
		projectJsonStr.append("{ ");
		projectJsonStr.append(
				"  createDate:{$dateToString:{ format: \"%Y-%m\", date:{$add:[ \"$createDate\",+28800000]}}}, ");
		projectJsonStr.append("  parkIds :1, ");
		projectJsonStr.append("  parkId :1, ");
		projectJsonStr.append("  buttonType : 1 ");
		projectJsonStr.append("} ");

		final DBObject project = new BasicDBObject("$project", JSON.parse(projectJsonStr.toString()));
		_log.info("$project is {}", project);

		StringBuffer groupJsonStr_1 = new StringBuffer();
		groupJsonStr_1.append("{ ");
		groupJsonStr_1.append("  _id : {\"createDate\":\"$createDate\",\"parkId\":\"$parkId\", \"buttonType\":\"$buttonType\"}, ");
		groupJsonStr_1.append("  total :{$sum:1} ");
		groupJsonStr_1.append("} ");
		final DBObject group_1 = new BasicDBObject("$group", JSON.parse(groupJsonStr_1.toString()));
		_log.info("$group_1 is {}", group_1);

		StringBuffer groupJsonStr_2 = new StringBuffer();
		groupJsonStr_2.append("{ ");
		groupJsonStr_2.append("  _id : {\"createDate\":\"$_id.createDate\",\"parkId\":\"$_id.parkId\"}, ");
		groupJsonStr_2.append("  itemsSold:{ $push:  { buttonType: \"$_id.buttonType\", total: \"$total\" } }");
		groupJsonStr_2.append("} ");
		final DBObject group_2 = new BasicDBObject("$group", JSON.parse(groupJsonStr_2.toString()));
		_log.info("$group_2 is {}", group_2);

		List<AggregationOperation> agglist = new ArrayList<AggregationOperation>();
		agglist.add(Aggregation.match(matchCrieria));
		agglist.add(new AggregationOperation() {
			@Override
			public DBObject toDBObject(AggregationOperationContext context) {
				return project;
			}

		});
		agglist.add(new AggregationOperation() {
			@Override
			public DBObject toDBObject(AggregationOperationContext context) {
				return group_1;
			}

		});

		agglist.add(new AggregationOperation() {
			@Override
			public DBObject toDBObject(AggregationOperationContext context) {
				return group_2;
			}

		});

		return agglist;
	}

	private List<AggregationOperation> buildAggredation_passMonth(StatisPassMonthExample example) {
		Criteria matchCrieria = new Criteria();
		List<Integer> parkIdlist = new ArrayList<Integer>();
		
		if(example.getParkId() != null){
			parkIdlist.add(Integer.valueOf(example.getParkId()));
		}else if(!ListUtil.isEmpty(example.getInParks())){
			parkIdlist.addAll(example.getInParks());
		}
//		if (!ListUtil.isEmpty(example.getInParks())) {
//			parkIdlist.addAll(example.getInParks());
//		}
//		if (example.getParkId() != null && !parkIdlist.contains(Integer.valueOf(example.getParkId()))) {
//			parkIdlist.add(Integer.valueOf(example.getParkId()));
//		}

		if (!ListUtil.isEmpty(parkIdlist)) {
			matchCrieria.and("parkId").in(parkIdlist);
		}

		// 由于java驱动操作mongodb 时间有８小时误差
		StringBuffer projectJsonStr = new StringBuffer();
		projectJsonStr.append("{ ");// %Y-%m-%d
		projectJsonStr
				.append("  oPTimeStr:{$dateToString:{ format: \"%Y-%m\", date: {$add:[\"$oPTime\",+28800000]}}}, ");
		projectJsonStr.append("  during :1, ");
		projectJsonStr.append("  oPName:1, ");
		projectJsonStr.append("  outTimes :1, ");
		projectJsonStr.append("  lostCard :1, ");
		projectJsonStr.append("  enterTimes :1, ");
		projectJsonStr.append("  payCard :1, ");
		projectJsonStr.append("  money :1, ");
		projectJsonStr.append("  offPay :1, ");
		projectJsonStr.append("  parkId :1, ");
		projectJsonStr.append("  monthPay :1, ");
		projectJsonStr.append("  saveCardPay :1, ");
		projectJsonStr.append("  enManual :1, ");
		projectJsonStr.append("  outManual :1, ");
		projectJsonStr.append("  freeTimes :1, ");
		projectJsonStr.append("  parkName :1, ");
		projectJsonStr.append("  noCardTimes :1, ");
		projectJsonStr.append("  feeAheadMoney :1, ");
		projectJsonStr.append("  calcMonthPay :1, ");
		projectJsonStr.append("  calcSaveCardPay :1, ");
		projectJsonStr.append("  oPTime :1, ");
		projectJsonStr.append("  calcMoney :1 ");
		projectJsonStr.append("} ");

		final DBObject project = new BasicDBObject("$project", JSON.parse(projectJsonStr.toString()));
		_log.info("$project is {}", project);

		StringBuffer groupJsonStr_1 = new StringBuffer();
		groupJsonStr_1.append("{ ");
		groupJsonStr_1.append("  _id : {\"oPTimeStr\":\"$oPTimeStr\", \"oPName\":\"$oPName\", \"parkName\":\"$parkName\"}, ");
		groupJsonStr_1.append("  during:{$sum:\"$during\"}, ");
		groupJsonStr_1.append("  outTimes:{$sum:\"$outTimes\"}, ");
		groupJsonStr_1.append("  lostCard:{$sum:\"$lostCard\"}, ");
		groupJsonStr_1.append("  enterTimes:{$sum:\"$enterTimes\"}, ");
		groupJsonStr_1.append("  payCard:{$sum:\"$payCard\"}, ");
		groupJsonStr_1.append("  money:{$sum:\"$money\"}, ");
		groupJsonStr_1.append("  offPay:{$sum:\"$offPay\"}, ");
		groupJsonStr_1.append("  monthPay:{$sum:\"$monthPay\"}, ");
		groupJsonStr_1.append("  saveCardPay:{$sum:\"$saveCardPay\"}, ");
		groupJsonStr_1.append("  enManual:{$sum:\"$enManual\"}, ");
		groupJsonStr_1.append("  outManual:{$sum:\"$outManual\"}, ");

		groupJsonStr_1.append("  freeTimes:{$sum:\"$freeTimes\"}, ");
		groupJsonStr_1.append("  noCardTimes:{$sum:\"$noCardTimes\"}, ");
		groupJsonStr_1.append(" feeAheadMoney:{$sum:\"$feeAheadMoney\"}, ");
		groupJsonStr_1.append("  calcMonthPay:{$sum:\"$calcMonthPay\"}, ");
		groupJsonStr_1.append(" calcSaveCardPay:{$sum:\"$calcSaveCardPay\"}, ");
		groupJsonStr_1.append("  calcMoney:{$sum:\"$calcMoney\"} ");
		groupJsonStr_1.append("} ");
		final DBObject group_1 = new BasicDBObject("$group", JSON.parse(groupJsonStr_1.toString()));
		_log.info("$group_1 is {}", group_1);

		List<AggregationOperation> agglist = new ArrayList<AggregationOperation>();
		agglist.add(Aggregation.match(matchCrieria));
		agglist.add(new AggregationOperation() {
			@Override
			public DBObject toDBObject(AggregationOperationContext context) {
				return project;
			}

		});
		agglist.add(new AggregationOperation() {
			@Override
			public DBObject toDBObject(AggregationOperationContext context) {
				return group_1;
			}

		});

		// agglist.add(new AggregationOperation() {
		// @Override
		// public DBObject toDBObject(AggregationOperationContext context) {
		// return group_2;
		// }
		//
		// });

		return agglist;
	}

	private List<AggregationOperation> buildAggredation_interMonth_segment(StatisInterMonthExample example) {
		Criteria matchCrieria = new Criteria();
//		List<Integer> parkIdlist = new ArrayList<Integer>();
//		if (!ListUtil.isEmpty(example.getInParks())) {
//			parkIdlist.addAll(example.getInParks());
//		}
//		if (!StringUtils.isBlank(example.getParkId()) && !parkIdlist.contains(Integer.valueOf(example.getParkId()))) {
//			parkIdlist.add(Integer.valueOf(example.getParkId()));
//		}
		
		List<String> parkIdlist = new ArrayList<String>();
		if(!StringUtils.isBlank(example.getParkId())){
			parkIdlist.add(example.getParkId());
		}else if(!ListUtil.isEmpty(example.getInParks())){
			parkIdlist.addAll(example.getStrInParks());
		}
		
//		if (!ListUtil.isEmpty(parkIdlist)) {
//			matchCrieria.and("parkId").in(parkIdlist);
//		}
		
		List<Criteria>   andCrieria=new ArrayList<Criteria>();
		if (!ListUtil.isEmpty(parkIdlist)&&!ListUtil.isEmpty(example.getNoInParks())) {
//			andCrieria.andOperator(Criteria.where("parkId").in(parkIdlist),Criteria.where("parkId").nin(example.getNoInParks()));
			andCrieria.add(Criteria.where("parkId").in(parkIdlist));
			andCrieria.add(Criteria.where("parkId").nin(example.getNoInParks()));
		}else if(!ListUtil.isEmpty(parkIdlist)){
//			andCrieria.and("parkId").in(parkIdlist);
			andCrieria.add(Criteria.where("parkId").in(parkIdlist));
		}else if(!ListUtil.isEmpty(example.getNoInParks())){
//			andCrieria.and("parkId").nin(example.getNoInParks());
			andCrieria.add(Criteria.where("parkId").nin(example.getNoInParks()));
		}
		
		if (example.getStartTime() != null && example.getEndTime() != null) {
//			andCrieria.andOperator(Criteria.where("createDate").gte(example.getStartTime()),
//					Criteria.where("createDate").lte(example.getEndTime()));
			andCrieria.add(Criteria.where("createDate").gte(example.getStartTime()));
			andCrieria.add(Criteria.where("createDate").lte(example.getEndTime()));
		} else if (example.getStartTime() != null) {
//			andCrieria.andOperator(Criteria.where("createDate").gte(example.getStartTime()));
			andCrieria.add(Criteria.where("createDate").gte(example.getStartTime()));
		} else if (example.getEndTime() != null) {
//			andCrieria.andOperator(Criteria.where("createDate").lte(example.getEndTime()));
			andCrieria.add(Criteria.where("createDate").lte(example.getEndTime()));
		}
		if(!ListUtil.isEmpty(andCrieria)){
			matchCrieria.andOperator(andCrieria.toArray(new Criteria[andCrieria.size()]));
		}
		StringBuffer groupJsonStr = new StringBuffer();
		groupJsonStr.append("{ ");
		groupJsonStr.append("  _id:{buttonType:\"$buttonType\",parkId:\"$parkId\"}, ");
		groupJsonStr.append("  total :{$sum:1} ");
		groupJsonStr.append("} ");
		final DBObject group = new BasicDBObject("$group", JSON.parse(groupJsonStr.toString()));
		_log.info("$group is {}", group);
		
		StringBuffer groupJsonStr_02 = new StringBuffer();
		groupJsonStr_02.append("{ ");
		groupJsonStr_02.append("  _id : {\"parkId\":\"$_id.parkId\"}, ");
		groupJsonStr_02.append("  itemsSold:{ $push:  { buttonType: \"$_id.buttonType\", total: \"$total\" } } ");
		groupJsonStr_02.append("} ");
		final DBObject group_02 = new BasicDBObject("$group", JSON.parse(groupJsonStr_02.toString()));
		_log.info("$group is {}", group_02);

		List<AggregationOperation> agglist = new ArrayList<AggregationOperation>();
		agglist.add(Aggregation.match(matchCrieria));
		agglist.add(new AggregationOperation() {
			@Override
			public DBObject toDBObject(AggregationOperationContext context) {
				return group;
			}

		});
		agglist.add(new AggregationOperation() {
			@Override
			public DBObject toDBObject(AggregationOperationContext context) {
				return group_02;
			}

		});
		_log.info("agglist is {}", agglist);
		return agglist;
	}

	private String buildTimeStr_interMonth_segment(StatisInterMonthExample example) {
		String timeStr = "";
		if (example.getStartTime() != null && example.getEndTime() != null) {
			timeStr = DateUtils.formatDate(example.getStartTime(), DateUtils.DATE_SHORT_DATEONLY) + " 至 "
					+ DateUtils.formatDate(example.getEndTime(), DateUtils.DATE_SHORT_DATEONLY);
		} else if (example.getStartTime() != null && example.getEndTime() == null) {
			timeStr = DateUtils.formatDate(example.getStartTime(), DateUtils.DATE_SHORT_DATEONLY);
		} else if (example.getStartTime() == null && example.getEndTime() != null) {
			timeStr = DateUtils.formatDate(example.getEndTime(), DateUtils.DATE_SHORT_DATEONLY);
		}
		return timeStr;
	}

	private String buildTimeStr_passMonth_segment(StatisPassMonthExample example) {
		String timeStr = "";
		if (example.getStartTime() != null && example.getEndTime() != null) {
			timeStr = DateUtils.formatDate(example.getStartTime(), DateUtils.DATE_SHORT_DATEONLY) + " 至 "
					+ DateUtils.formatDate(example.getEndTime(), DateUtils.DATE_SHORT_DATEONLY);
		} else if (example.getStartTime() != null && example.getEndTime() == null) {
			timeStr = DateUtils.formatDate(example.getStartTime(), DateUtils.DATE_SHORT_DATEONLY);
		} else if (example.getStartTime() == null && example.getEndTime() != null) {
			timeStr = DateUtils.formatDate(example.getEndTime(), DateUtils.DATE_SHORT_DATEONLY);
		}
		return timeStr;
	}

	public List<InterMonth> interMonth_segment(StatisInterMonthExample example, int jumpPage, int pageLength) {
		String tablename_terminallog = MongodbConstant.TABLENAME_TERMINALLOG;
		List<InterMonth> result = new ArrayList<InterMonth>();
		List<AggregationOperation> aggOperList = buildAggredation_interMonth_segment(example);
		// aggOperList.add(Aggregation.skip((jumpPage - 1) * pageLength));
		// aggOperList.add(Aggregation.limit(pageLength));
		Aggregation agg = Aggregation.newAggregation(aggOperList);
		_log.info("$Aggregation is {}", agg.toString());
		AggregationResults<DBObject> aggResult = mongoTemplate.aggregate(agg, tablename_terminallog, DBObject.class);
		List<DBObject> dbobjlist = aggResult.getMappedResults();
		Map<Integer,String> parkId2name=new HashMap<Integer,String>();
		for (DBObject dbobj : dbobjlist) {
			InterMonth intermonth = new InterMonth();
			intermonth.setTimeStr(buildTimeStr_interMonth_segment(example));
//			int buttonType = (int) dbobj.get("buttonType");
//			int total = (int) dbobj.get("total");
			String parkIdStr=(String) dbobj.get("parkId");
			String parkName="";
			if(!StringUtils.isBlank(parkIdStr)){
				if(parkId2name.containsKey(Integer.valueOf(parkIdStr))){
					parkName=parkId2name.get(Integer.valueOf(parkIdStr));
				}else{
					TbParkspace tbParkspace=parkCacheInter.queryParkSpace(Integer.valueOf(parkIdStr));
					parkName=tbParkspace==null?"":tbParkspace.getName();
					parkId2name.put(Integer.valueOf(parkIdStr), parkName);
				}
			}
			intermonth.setParkName(parkName);
			int carLockNum=0;
			int feeNum=0;
			int generaNum=0;
			int hisRecordNum=0;
			int invitNum=0;
			int reserveNum=0;
			List<DBObject> itemsSold = (List<DBObject>) dbobj.get("itemsSold");
			for (DBObject info : itemsSold) {
				int buttonType = (int) info.get("buttonType");
				int num = (int) info.get("total");
				if (ButtonTypeEnum.carLock.getType() == buttonType) {
					carLockNum=num;
				} else if (ButtonTypeEnum.fee.getType() == buttonType) {
					feeNum=num;
				} else if (ButtonTypeEnum.generaFee.getType() == buttonType) {
					generaNum=num;
				} else if (ButtonTypeEnum.hisRecord.getType() == buttonType) {
					hisRecordNum=num;
				} else if (ButtonTypeEnum.invit.getType() == buttonType) {
					invitNum=num;
				} else if (ButtonTypeEnum.reserve.getType() == buttonType) {
					reserveNum=num;
				}

			}
			
			intermonth.setCarLockNum(carLockNum);
			intermonth.setFeeNum(feeNum);
			intermonth.setGeneraNum(generaNum);
			intermonth.setHisRecordNum(hisRecordNum);
			intermonth.setHisRecordNum(hisRecordNum);
			intermonth.setInvitNum(invitNum);
			intermonth.setParkName(parkName);
			intermonth.setReserveNum(reserveNum);
			result.add(intermonth);
//			if (ButtonTypeEnum.carLock.getType() == buttonType) {
//				intermonth.setCarLockNum(total);
//			} else if (ButtonTypeEnum.fee.getType() == buttonType) {
//				intermonth.setFeeNum(total);
//			} else if (ButtonTypeEnum.generaFee.getType() == buttonType) {
//				intermonth.setGeneraNum(total);
//			} else if (ButtonTypeEnum.hisRecord.getType() == buttonType) {
//				intermonth.setHisRecordNum(total);
//			} else if (ButtonTypeEnum.invit.getType() == buttonType) {
//				intermonth.setInvitNum(total);
//			} else if (ButtonTypeEnum.reserve.getType() == buttonType) {
//				intermonth.setReserveNum(total);
//			}

		}
		return result;
	}

	public long passMonth_report_total(StatisPassMonthExample example) {

		// 表名
		String tablenamePassDay = MongodbConstant.TABLENAME_PASS_DAY_REPORT;
		// 得到日期字符串
		List<PassMonth> result = new ArrayList<PassMonth>();
		Criteria matchCrieria = new Criteria();
		List<Integer> parkIdlist = new ArrayList<Integer>();
		matchCrieria.where("_id").not();
		if (example.getStartTime() != null && example.getEndTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").gte(example.getStartTime()),
					Criteria.where("oPTime").lte(example.getEndTime()));
		} else if (example.getStartTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").gte(example.getStartTime()));
		} else if (example.getEndTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").lte(example.getEndTime()));
		}

		if (example.getParkId() != null) {
			parkIdlist.add(example.getParkId());
		} else if (!ListUtil.isEmpty(example.getInParks())) {
			parkIdlist.addAll(example.getInParks());
		}
		if (!ListUtil.isEmpty(parkIdlist)) {
			matchCrieria.and("parkId").in(parkIdlist);
		}

		// 构建查询条件

		Query query = Query.query(matchCrieria);

		long total = mongoTemplate.count(query, tablenamePassDay);

		return total;

	}

	public List<PassMonth> passMonth_segment(StatisPassMonthExample example, int jumpPage, int pageLength) {
		// 表名
		String tablenamePassDay = MongodbConstant.TABLENAME_PASS_DAY_REPORT;
		// 得到日期字符串
		List<PassMonth> result = new ArrayList<PassMonth>();
		Criteria matchCrieria = new Criteria();
		List<Integer> parkIdlist = new ArrayList<Integer>();
		matchCrieria.where("_id").not();
		if (example.getStartTime() != null && example.getEndTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").gte(example.getStartTime()),
					Criteria.where("oPTime").lte(example.getEndTime()));
		} else if (example.getStartTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").gte(example.getStartTime()));
		} else if (example.getEndTime() != null) {
			matchCrieria.andOperator(Criteria.where("oPTime").lte(example.getEndTime()));
		}

		if (example.getParkId() != null) {
			parkIdlist.add(example.getParkId());
		} else if (!ListUtil.isEmpty(example.getInParks())) {
			parkIdlist.addAll(example.getInParks());
		}
		if (!ListUtil.isEmpty(parkIdlist)) {
			matchCrieria.and("parkId").in(parkIdlist);
		}

		// 构建查询条件

		Query query = Query.query(matchCrieria);
		query.with(new Sort(new Order(Direction.DESC, "oPTime")));
		query.skip((jumpPage - 1) * pageLength);
		query.limit(pageLength);
		_log.info(matchCrieria.toString());
		_log.info(query.toString());
		List<NcPassDayReport> list = mongoTemplate.find(query, NcPassDayReport.class, tablenamePassDay);
		for (NcPassDayReport info : list) {
			int freeCarNum = info.getFreeTimes();
			int inCheckNum = info.getEnterTimes();
			int inManualNum = info.getEnManual();
			int monthFee = info.getMonthPay();
			int monthShouldFee = info.getCalcMonthPay();
			String operator = info.getoPName();
			int outCheckNum = info.getOutTimes();
			int parkFee = info.getMoney();
			int workTime = info.getDuring();
			int totalFee = monthFee + parkFee;
			// 出场手动放行次数
			int outManualNum = info.getOutManual();
			String parkName=info.getParkName();
			// String timeStr=buildTimeStr_passMonth_segment(example);
			String timeStr = DateUtils.formatDate(info.getoPTime(), DateUtils.DATE_SHORT_DATEONLY);
			PassMonth passmonth = new PassMonth();
			passmonth.setFreeCarNum(freeCarNum);
			passmonth.setInCheckNum(inCheckNum);
			passmonth.setInManualNum(inManualNum);
			passmonth.setMonthFee(monthFee);
			passmonth.setMonthShouldFee(monthShouldFee);
			passmonth.setOperator(operator);
			passmonth.setOutCheckNum(outCheckNum);
			passmonth.setParkFee(parkFee);
			passmonth.setTotalFee(totalFee);
			passmonth.setTotalFee(totalFee);
			passmonth.setWorkTime(workTime);
			passmonth.setTimeStr(timeStr);
			passmonth.setOutManualNum(outManualNum);
			passmonth.setParkName(parkName);
			result.add(passmonth);
		}

		return result;

	}

	public List<InterMonth> interMonth_month(StatisInterMonthExample example, int jumpPage, int pageLength) {
		String tablename_terminallog = MongodbConstant.TABLENAME_TERMINALLOG;
		List<InterMonth> result = new ArrayList<InterMonth>();
		List<AggregationOperation> aggOperList = buildAggredation_interMonth(example);
		aggOperList.add(Aggregation.sort(new Sort(Direction.DESC, "_id.createDate")));
		aggOperList.add(Aggregation.skip((jumpPage - 1) * pageLength));
		aggOperList.add(Aggregation.limit(pageLength));
		Aggregation agg = Aggregation.newAggregation(aggOperList);
		_log.info("$Aggregation is {}", agg.toString());

		AggregationResults<DBObject> aggResult = mongoTemplate.aggregate(agg, tablename_terminallog, DBObject.class);
		Map<Integer,String> parkId2name=new HashMap<Integer,String>();

		List<DBObject> dbobjlist = aggResult.getMappedResults();
		for (DBObject info : dbobjlist) {
			_log.info(info.toString());
			InterMonth intermonth = new InterMonth();
			result.add(intermonth);
			String timeStr = (String) info.get("createDate");
			String parkIdStr=(String) info.get("parkId");
			String parkName="";
			if(!StringUtils.isBlank(parkIdStr)){
				if(parkId2name.containsKey(Integer.valueOf(parkIdStr))){
					parkName=parkId2name.get(Integer.valueOf(parkIdStr));
				}else{
					TbParkspace tbParkspace=parkCacheInter.queryParkSpace(Integer.valueOf(parkIdStr));
					parkName=tbParkspace==null?"":tbParkspace.getName();
					parkId2name.put(Integer.valueOf(parkIdStr), parkName);
				}
			}
			intermonth.setParkName(parkName);
			intermonth.setTimeStr(timeStr);
			List<DBObject> itemsSold = (List<DBObject>) info.get("itemsSold");
			for (DBObject dbobj : itemsSold) {
				int buttonType = (int) dbobj.get("buttonType");
				int total = (int) dbobj.get("total");
				if (ButtonTypeEnum.carLock.getType() == buttonType) {
					intermonth.setCarLockNum(total);
				} else if (ButtonTypeEnum.fee.getType() == buttonType) {
					intermonth.setFeeNum(total);
				} else if (ButtonTypeEnum.generaFee.getType() == buttonType) {
					intermonth.setGeneraNum(total);
				} else if (ButtonTypeEnum.hisRecord.getType() == buttonType) {
					intermonth.setHisRecordNum(total);
				} else if (ButtonTypeEnum.invit.getType() == buttonType) {
					intermonth.setInvitNum(total);
				} else if (ButtonTypeEnum.reserve.getType() == buttonType) {
					intermonth.setReserveNum(total);
				}

			}
		}
		return result;
	}
	
	public List<PassMonth> passMonth_month(StatisPassMonthExample example, int jumpPage, int pageLength) {
		String tablenamePassDayReport = MongodbConstant.TABLENAME_PASS_DAY_REPORT;
		List<PassMonth> result = new ArrayList<PassMonth>();
		List<AggregationOperation> aggOperList = buildAggredation_passMonth(example);
		aggOperList.add(Aggregation.sort(new Sort(Direction.DESC, "_id.oPTimeStr")));
		aggOperList.add(Aggregation.skip((jumpPage - 1) * pageLength));
		aggOperList.add(Aggregation.limit(pageLength));
		Aggregation agg = Aggregation.newAggregation(aggOperList);
		_log.info("$Aggregation is {}", agg.toString());

		AggregationResults<NcPassDayReport> aggResult = mongoTemplate.aggregate(agg, tablenamePassDayReport,
				NcPassDayReport.class);

		List<NcPassDayReport> dbobjlist = aggResult.getMappedResults();
		for (NcPassDayReport info : dbobjlist) {
			_log.info(info.toString());
			// 免费车次数
			int freeCarNum = info.getFreeTimes();
			// 进场次数
			int inCheckNum = info.getEnterTimes();
			// 进场手动放行次数
			int inManualNum = info.getEnManual();
			// 月牌实收(分)
			int monthFee = info.getMonthPay();
			// 月牌应收(分)
			int monthShouldFee = info.getCalcMonthPay();
			// 操作员
			String operator = info.getoPName();
			// 出场手动放行次数
			int outManualNum = info.getOutManual();
			String timeStr = info.getoPTimeStr();
			int outCheckNum = info.getOutTimes();
			// 停车费
			int parkFee = info.getMoney();
			// 上班时间
			int workTime = info.getDuring();
			// 总计
			int totalFee = monthFee + parkFee;
			String parkName=info.getParkName();
			PassMonth passmonth = new PassMonth();
			passmonth.setFreeCarNum(freeCarNum);
			passmonth.setInCheckNum(inCheckNum);
			passmonth.setInManualNum(inManualNum);
			passmonth.setMonthFee(monthFee);
			passmonth.setMonthShouldFee(monthShouldFee);
			passmonth.setOperator(operator);
			passmonth.setOutCheckNum(outCheckNum);
			passmonth.setParkFee(parkFee);
			passmonth.setTotalFee(totalFee);
			passmonth.setWorkTime(workTime);
			passmonth.setTimeStr(timeStr);
			passmonth.setOutManualNum(outManualNum);
			passmonth.setParkName(parkName);
			result.add(passmonth);
		}
		return result;
	}

}
